package util;

import java.sql.*;
import java.util.Properties;

public class DBUtil {
    //获取数据库连接对象
    private static String url;
    private static String user;
    private static String password;

    static {
        //加载数据库驱动
        try {
            Properties config = new Properties();
            config.load(DBUtil.class.getResourceAsStream("jdbc.properties"));
            url = config.getProperty("jdbc.url");
            user = config.getProperty("jdbc.user");
            password = config.getProperty("jdbc.password");
            Class.forName(config.getProperty("jdbc.driver", "com.mysql.jdbc.Driver"));
        } catch (Exception ex) {
            ex.printStackTrace();
            System.exit(0);
        }
    }

    private DBUtil() {
    }

    /**
     * 获取数据库连接
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, user, password);
    }

    public static void close(Connection conn, Statement stmt) {
        try {
            stmt.close();
        } catch (Exception e) {
        }
        try {
            conn.close();
        } catch (Exception e) {
        }
    }

    public static void close(Connection conn, Statement stmt, ResultSet rs) {
        try {
            rs.close();
        } catch (Exception e) {
        }
        close(conn, stmt);
    }
}
